#!/usr/bin/python
# -*- coding: utf-8 -*-

################################################################################
#
# Copyright (c) 2020 openEuler.org, Inc. All Rights Reserved
#
################################################################################
"""
Email notification of incorrect data

Authors: xiaojianghui
Date:    10/22/2020 11:01 AM
"""

import smtplib
import os
import email.mime.multipart
import email.mime.text
import email.mime.application as application
import email.utils


def send_email(smtp_host, smtp_port, send_addr, password, recipient_addrs, path, subject='', content=''):
    """
        send email
    :param smtp_host:smpt.gmail.com
    :param smtp_port:587
    :param send_addr:
    :param password:
    :param recipient_addrs:
    :param path:
    :param subject: title
    :param content: content
    :return:None
    """
    msg = email.mime.multipart.MIMEMultipart()
    msg['from'] = email.utils.formataddr(["cve-manager", send_addr])
    msg['to'] = recipient_addrs
    msg['subject'] = subject
    content = content
    txt = email.mime.text.MIMEText(content, 'plain', 'utf-8')
    msg.attach(txt)
    # Add attachment address
    files = os.listdir(path)
    if not files:
        print("No data sheet")
        return
    for fileName in files:
        part = application.MIMEApplication(open(path + '/' + fileName, 'rb').read())
        part.add_header('Content-Disposition', 'attachment', filename=fileName)
        msg.attach(part)
    try:
        smtp_ssl_client = smtplib.SMTP(smtp_host, smtp_port)
        # smtp_ssl_client.ehlo()
        # smtp_ssl_client.starttls()
        # login_res = smtp_ssl_client.login(send_addr, password)
        # print("Login result:login_res=", login_res)
        # if login_res and login_res[0] == 235:
        #     print("login successful，code=[login_res[0]]")
        #     smtp_ssl_client.sendmail(send_addr, recipient_addrs, str(msg))
        #     print("mail has been send successfully. message: ", str(msg))
        #     smtp_ssl_client.quit()
        # else:
        #     print("login failed,code= ", login_res[0])
        smtp_ssl_client.sendmail(send_addr, recipient_addrs, str(msg))
        print("mail has been send successfully. message: ", str(msg))
        smtp_ssl_client.quit()
    except SystemExit as e:
        print("Failed to send,Exception:e= ", e)
